<?php

namespace App\Trip\Epidemic\Juhe;

use App\Models\Common\Area\Area;
use App\Trip\Translate\Niutrans\Translation;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Cache;

class Aggregation
{
    private string $language;

    public function __construct()
    {
        $this->language = 'uy';
    }

    public function setLanguage($language): self
    {
        $this->language = $language;
        return $this;
    }

    /**
     * 防疫政策
     *
     * @throws Exception
     * @throws GuzzleException
     */
    public function policy(Area $from, Area $to): array
    {
        $city         = new City();
        $policy       = new Policy();
        $from_city_id = $city->query()->getCodeByName($from->getAreaName());
        $to_city_id   = $city->query()->getCodeByName($to->getAreaName());
        $cache_key    = "Epidemic:policy:{$from_city_id}:{$to_city_id}:{$this->language}";
        if (Cache::has($cache_key)) {
            return Cache::get($cache_key);
        }
        $res = $policy->query([
            'from' => $from_city_id,
            'to'   => $to_city_id,
        ]);

        $ret = [
            "from_info" => [
                "city_code"    => '',
                "city_name"    => $from->getAreaName(),
                "city_name_uy" => $from->getAreaNameUy(),
                "in_desc"      => (new Translation($res->getFromInDesc()))->setTo($this->language)->translate()->getTranslation(),
                "out_desc"     => (new Translation($res->getFromOutDesc()))->setTo($this->language)->translate()->getTranslation(),
                "risk_level"   => $res->getFromRiskLevel(),
            ],
            "to_info"   => [
                "city_code"    => '',
                "city_name"    => $to->getAreaName(),
                "city_name_uy" => $to->getAreaNameUy(),
                "in_desc"      => (new Translation($res->getToInDesc()))->setTo($this->language)->translate()->getTranslation(),
                "out_desc"     => (new Translation($res->getToOutDesc()))->setTo($this->language)->translate()->getTranslation(),
                "risk_level"   => $res->getToRiskLevel(),
            ],
        ];
        Cache::put($cache_key, $ret, config('trip.ttl.day'));
        return $ret;
    }


}